<?php
	//内容管理  控制器
class InfoControl extends checkLogin{
	function index(){}




	// 自定义kedit编辑器 图片上传处理
	function kedit_upload(){

	}

	/**
	 * 首页图片展示
	 * @return [type] [description]
	 */
	function indexImgs(){

		$db = M('indeximgs');
		$total = $db->count();
		$page = new page($total,10,6,2);
		
		$list = $db->limit($page->limit())->all();
		
		$this->assign('list',$list);
		$this->assign('page',$page->show(4));//分页字符串
		$this->display();
	}

	function indexImgAjax(){
		$id = @$_POST['id'];
		$zt = @$_POST['zt'];
		$zt = $zt?"0":"1";
		$db = M('indeximgs');
		$data = array(
				'id'=>$id,
				'isshow'=>$zt,
			);
		$result  = $db->update($data);

		echo json_encode($result);
		exit;
		if($result){
					$sql = "update ica_infoList set navshow=$zt where id=$id or (path like '".$result['path'].'-'.$id."%')";
					$db->runSql($sql);
			
				
					$sql ="select concat(`id`,'_f') as id from ica_infoList where id=$id or (path like '".$result['path'].'-'.$id."%')";
					$ids = $db->query($sql);
					//$ids = $this->where("id=$id or (path like '".$result['path'].'-'.$id."')")->all();
					//return $ids;
					//记录日志
					$id ="";
					foreach($ids as $v){
						$id.=$v['id'].",";
					}
					$id = trim($id,',');
					$title = "ajax更新内容分类前台显示";
					$content = $title.",<br/>更新分类id：".$id;
					actLog($title,$content);
					echo json_encode(array('ids'=>$ids));
		}

	}

	/**
	 * 编辑首页图片
	 * @return [type] [description]
	 */
	function editIndexImg(){
		if(IS_POST){
			$id = $this->_post('id');
			if(!$id){
				$this->error('error');
				exit;
			}
			$db = M('indeximgs');
			$odata = $db->field('id,src')->where("id=$id")->one();//旧数据

			$thumb = 0; //是否缩略图
			$width = $this->_post('w');
			$height = $this->_post('h');
			if($width && $height){
				$thumb = 1;
			}
			//实例化上传类
			$up = new upload('Public/images/indexImg',array("jpg","jpeg","png","gif"),4000000,0,$thumb,array($width,$height,1));
			$data = $up->upload();
		

			// 判断删除不需要图片
			if($data && $thumb){//保留缩略图，删除原图
				$file = PATH_ROOT.'/'.$data[0]['path'];
				if(is_file($file)) unlink($file);
				$_POST['src'] = $data[0]['thumb'];
			}else{
				// 保留原图删除缩略图
				$_POST['src'] = $data[0]['path'];
			}
			
			if($db->save()){
				// 删除旧文件
				if(!empty($_POST['src'])){
					$file = PATH_ROOT.'/'.$odata['src'];
					if(is_file($file)) unlink($file);
				}

				$this->success('修改首页图片成功');
				exit;
			}else{
				$this->error("修改首页图片失败");
				exit;
			}
			

		}elseif(IS_GET && isset($_GET['id'])){
			$id = $this->_get('id');
			$db = M('indeximgs');
			$data = $db->where("id=$id")->one();
			$this->assign('data',$data);
			$this->display();
		}

	}
	/**
	 * 添加首页图片
	 */
	function addIndexImg(){
		if(IS_POST){
			$thumb = 0; //是否缩略图
			$width = $this->_post('w');
			$height = $this->_post('h');
			if($width && $height){
				$thumb = 1;
			}


			//实例化上传类
			$up = new upload('Public/images/indexImg',array("jpg","jpeg","png","gif"),4000000,0,$thumb,array($width,$height,1));
			$data = $up->upload();
		

			// 判断删除不需要图片
			if($data && $thumb){//保留缩略图，删除原图
				$file = PATH_ROOT.'/'.$data[0]['path'];
				if(is_file($file)) unlink($file);
				$_POST['src'] = $data[0]['thumb'];
			}else{
				// 保留原图删除缩略图
				$_POST['src'] = $data[0]['path'];
			}
			
			if(M('indeximgs')->add()){
				$this->success('添加首页图片成功');
				exit;
			}else{
				$this->error("添加首页图片失败");
				exit;
			}
			

		}else{

			$this->display();
		}

	}
	//ajax内容分类前台显示
	function ajaxNavShow(){
		//echo json_encode('4444');exit;
		
		$id = @$_POST['id'];
		$zt = @$_POST['zt'];
		$zt = $zt?"0":"1";
		$db = M('infoList');
		$result  = $db->where('id='.$id)->one();
		if($result){
					$sql = "update ica_infoList set navshow=$zt where id=$id or (path like '".$result['path'].'-'.$id."%')";
					$db->runSql($sql);
			
				
					$sql ="select concat(`id`,'_f') as id from ica_infoList where id=$id or (path like '".$result['path'].'-'.$id."%')";
					$ids = $db->query($sql);
					//$ids = $this->where("id=$id or (path like '".$result['path'].'-'.$id."')")->all();
					//return $ids;
					//记录日志
					$id ="";
					foreach($ids as $v){
						$id.=$v['id'].",";
					}
					$id = trim($id,',');
					$title = "ajax更新内容分类前台显示";
					$content = $title.",<br/>更新分类id：".$id;
					actLog($title,$content);
					echo json_encode(array('ids'=>$ids));
		}


		
	}

	//ajax内容分类使用隐藏
	function infoListAjax(){
		//echo json_encode('4444');exit;
		
		$id = @$_POST['id'];
		$zt = @$_POST['zt'];
		$zt = $zt?"0":"1";
			$db = M('infoList');
		$result  = $db->where('id='.$id)->one();
		if($result){
					$sql = "update ica_infoList set isshow=$zt where id=$id or (path like '".$result['path'].'-'.$id."%')";
					$db->runSql($sql);
			
				
					$sql ="select `id` from ica_infoList where id=$id or (path like '".$result['path'].'-'.$id."%')";
					$ids = $db->query($sql);
					//$ids = $this->where("id=$id or (path like '".$result['path'].'-'.$id."')")->all();
					//return $ids;
					//记录日志
					$id ="";
					foreach($ids as $v){
						$id.=$v['id'].",";
					}
					$id = trim($id,',');
					$title = "ajax更新内容分类显示成功";
					$content = $title.",<br/>更新分类id：".$id;
					actLog($title,$content);
					echo json_encode(array('ids'=>$ids));
		}


		
	}

	//内容分类
	function infoList(){
		// $a = realpath('http://anxuan-china/admin.php');
		
		$db = K('infoList');
			$total = $db->count();
			$page = new page($total,10,6,2);
			$limit = $page->limit();
			$sql = "select `id`,`name`,`path`,`isshow`,`navshow`,`orders`,concat(`path`,'-',`id`) as ipath from ica_infoList order by ipath"." limit ".$limit['limit'];
			$r = $db->query($sql);

			$this->assign('list',$r);//显示数据
			//p($page->show());
			$this->assign('page',$page->show(4));//分页字符串
		$this->display();
	}
	//分类内容检索
	function infoSearch(){
		if(!empty($_POST['searchContent'])){//存在检索信息，显示检索结果
			$title = $_POST['sTitle'];
			$content = $_POST['searchContent'];
			if($title=='addtime'){//转换时间字符串格式
				$content = strtotime($content);
			}
			$db = M("info");
			$where = $title." like '%".$content."%'";
			$result = $db->where($where)->all();

			$this->assign('list',$result);
			$this->display("info.html");
		}else{//没有检索信息，输出检索表单

			$this->display("infoSearchForm.html");
		}
		
	}
	//显示所有文章内容列表
	function infoShow(){
		
		$order='addtime desc';
		if(!empty($_GET['sort'])){//排序条件
			$order=$_GET['sort'].' desc';
		}
		$db = K('infoList');
		$fenlei = $db->getList('','',1);
		$lid =isset($_GET['fenlei'])?$_GET['fenlei']:''; //分类id
		$where = "1 ";
		if($lid){ //进行分类筛选

			$lids = $db->getLids($lid);

			$where.="and lid in(".$lids.")";
		}

		$db = K('info');



		$total = $db->count($where);
		$page = new page($total,10,6);

		$result = $db->where($where)->order($order)->findAll($page->limit());


		$this->assign('fenlei',$fenlei); //分类下拉列表，含js判断
		$this->assign('page',$page->show(1));//分页
		$this->assign('list',$result);//文章内容数组
		$this->display();
	}
	function ajaxInfoShow(){
		$id = $_POST['id'];
		$isshow = $_POST['zt'];
		$db = M('info');
		if($db->update(array('id'=>$id,'isshow'=>$isshow))){
			$title = "异步修改文章内容使用显示";
			$zt = $isshow=='1'?'使用':'禁止';
			$content ="操作：".$title.",id为".$id."文章内容修改为：".$zt;
			actLog($title,$content);
			echo json_encode(array('id'=>$id,'isshow'=>$isshow));
			exit;
		}else{

		}
	}
	//添加文章内容
	function addInfo(){
		if(isset($_POST['title'])){//存在post，进行添加

			$db = M('info');
			$rs = $db->where("title='".$_POST['title']."'")->one();
			if($rs){
				$this->error('标题不能重复',__METH__);
				exit;
			}


			//获得封面图片
			$content = $_POST['content'];


			//获得描述
			$temp = '';
			if(!empty($_POST['des'])){
				$tmp = strip_tags($_POST['des']);
				$tmp = showShort($tmp,200);
			}else{
				$tmp = strip_tags($content);
				$tmp = showShort($tmp,200);
			}	
			//描述
			$_POST['des'] = $tmp;

			
			// 获得缩略图
			if(!empty($_FILES['coverimg']['name'])){//存在上传封面，进行上传处理
				

			
				$img_url = '';
				$img_thumb = '';
				

				//实例化上传类
				$up = new upload('Public/images/info',array("jpg","jpeg","png","gif"),2000000,0,1,array(270,216,1));

				
				$upfiles = $up->upload();
				
				if($upfiles){
					

					$_POST['coverimg_thumb'] = $upfiles[0]['thumb'];

					
					$_POST['coverimg'] = $upfiles[0]["path"];
				}



			}else{//不存在上传图，进场常规处理，提取正文图片
				$preg = "/<img\s+(.*)?src=\"(http:\/\/.+\.(jpg|gif|bmp|bnp))?\"(.*)?\/>/isU";  //匹配内容的第一张图片
				//$preg = "/<img(.*)src=\"([^"]+)\"[^>]+>/isU";
				preg_match_all($preg, $content,$matches,PREG_SET_ORDER);
			
				if(!empty($matches)){

					$img = new image();
					$file=$matches[0][2];
					$p = strchr($file,"upload");
					
					$ipath =  PATH_ROOT.'/'.$p;
					$name = time().'.jpg';
					$simgname = $img->thumb($ipath,$name,PATH_ROOT.'/Public/images/info',270,216,6);
				
					$p2 = strchr($simgname,"Public");

					$path = __ROOT__.'/'.$p2;
					
					$_POST['coverimg_thumb'] = $path;

					
					$_POST['coverimg'] = $matches[0][2];
				}
			}
			
			if($_POST['istop'] == 1){
				// 如果置顶，将另外已置顶取消置顶
				$s = $db->where('istop = 1')->update(array('istop'=>0));
			}

			
			$_POST['addtime'] = empty($_POST['addtime'])?time():strtotime($_POST['addtime']); //日期转换为时间戳

			$_POST['author'] = empty($_POST['author'])?$_SESSION['ica_uname']:$_POST['author']; //录入员
			
			
			$result = $db->add();
			$title = "添加文章";

			
			if($result){//插入成功
				$content = $title.":<span style='font-weight:bold;'>成功</span>, 文章id：".$db->getInsertId();
				actLog($title,$content);
				$this->success('添加成功',__CONTROL__.'/infoShow');
				exit;
			}else{//插入失败
				$content = $title.":<span style='font-weight:bold;color:#f60;'>失败</span>";
				actLog($title,$content);
				$this->success('添加失败',__METH__);
				exit;
			}	
		}else{//没有post，显示表单

		$db = K('infoList');
		$list = $db->getList();
		
		$this->assign('list',$list);
		$this->display();	
		}

	}
	//编辑分类
	function editInfo(){
		if(isset($_POST['title'])){//post数据，进行修改

			// //获得封面图片
			// $content = $_POST['content'];
			// $preg = "/<img\s+.*?src=\"(http:\/\/.+\.(jpg|gif|bmp|bnp))\".*\/>/isU";  //匹配内容的第一张图片
			// //$preg = "/<img(.*)src=\"([^"]+)\"[^>]+>/isU";
			// preg_match($preg, $content,$matches);
			// if(!empty($matches)){
			// 	$_POST['coverimg'] = $matches[1];
			// }
			

			//获得封面图片
			$content = $_POST['content'];

			//获得描述
			$temp = '';
			if(!empty($_POST['des'])){
				$tmp = strip_tags($_POST['des']);
				$tmp = showShort($tmp,200);
			}else{
				$tmp = strip_tags($content);
				$tmp = showShort($tmp,200);
			}	
			//描述
			$_POST['des'] = $tmp;



			// 获得缩略图
			if(!empty($_FILES['coverimg']['name'])){//存在上传封面，进行上传处理
				
				
			
				$img_url = '';
				$img_thumb = '';
				

				//实例化上传类
				$up = new upload('Public/images/info',array("jpg","jpeg","png","gif"),2000000,0,1,array(270,216,1));

				
				$upfiles = $up->upload();
				
				if($upfiles){
					

					$_POST['coverimg_thumb'] = $upfiles[0]['thumb'];

					
					$_POST['coverimg'] = $upfiles[0]["path"];
				}



			}else{//不存在上传图，进场常规处理，提取正文图片
				
				$preg = "/<img\s+(.*)?src=\"(http:\/\/.+\.(jpg|gif|bmp|bnp))?\"(.*)?\/>/isU";  //匹配内容的第一张图片
				//$preg = "/<img(.*)src=\"([^"]+)\"[^>]+>/isU";
				preg_match_all($preg, $content,$matches,PREG_SET_ORDER);
			
				if(!empty($matches)){

					$img = new image();
					$file=$matches[0][2];
					$p = strchr($file,"upload");
				
					$ipath =  PATH_ROOT.'/'.$p;
					$name = time().'.jpg';
					$simgname = $img->thumb($ipath,$name,PATH_ROOT.'/Public/images/info',270,216,6);
					$p2 = strchr($simgname,"Public");
					$path = __ROOT__.'/'.$p2;
					

					$_POST['coverimg_thumb'] = $path;

					
					$_POST['coverimg'] = $matches[0][2];
				}
			}
			
			


			$_POST['addtime'] = empty($_POST['addtime'])?time():strtotime($_POST['addtime']); //日期转换为时间戳

			$_POST['author'] = empty($_POST['author'])?$_SESSION['ica_uname']:$_POST['author']; //录入员
		
			$db = M('info');

			// 置顶处理
			if($_POST['istop'] == 1){
				// 如果置顶，将另外已置顶取消置顶
				$s = $db->where('istop = 1')->update(array('istop'=>0));
			}

			$result = $db->update();
			$title = "编辑文章";
			if($result){//更新成功
				$content = $title.":<span style='font-weight:bold;'>成功</span>, 文章id：".$result;
				actLog($title,$content);
				$this->success('更新成功',__CONTROL__.'/infoShow');
				exit;
			}else{//更新失败
				$content = $title.":<span style='font-weight:bold;color:#f60;'>失败</span>, 文章id：".$result;
				actLog($title,$content);
				$this->success('更新失败',__CONTROL__.'/infoShow');
				exit;
			}
		}else{//没有post信息，显示内容
					$id = @$_GET['id'];
		if(!$id){//没有id信息，返回检索页面
			go(__CONTROL__.'/infoSearch');
			exit;
		}

		$db = M('info');
		$result = $db->where("id=$id")->one();
		if(!$result){//没有相应id内容，返回
			go(__CONTROL__.'/infoSearch');
			exit;
		}
		$db = K("infoList");
			$sql = "select `id`,`name`,`path`,concat(`path`,'-',`id`) as ipath from ica_infoList where isshow=1 order by ipath";
			$r = $db->query($sql);

		$list = $db->getList($r,$result['lid']);
		//获得分类下啦列表
		$this->assign('list',$list);//分类列表
		$this->assign('data',$result);
		$this->display();	
		}



	}

	//删除文章
	function delInfo(){
		$id = @$_GET['id'];
		if(!isset($_GET['id'])){
			go(__CONTROL__.'/infoShow');
			exit;
		}
		$db = M('info');
		$result = $db->where("id=$id")->one();
		if(!$result) {
			go(__CONTROL__.'/infoShow');
			exit;
		}
		if($db->del($_GET['id'])){
			$title = "删除文章";
			$content = "操作：".$title." ；删除id为：".$_GET['id'];
			actLog($title,$content);
			$this->success('删除成功',__CONTROL__.'/infoShow');
			exit;
		}else{
			$this->success('删除失败',__CONTROL__.'/infoShow');
			exit;
		}
	}
	//添加分类
	function addList(){
		if(!empty($_POST['name'])){//存在post数据，进行添加

			$db = K('infoList');
			//
			$navshow = $this->_post('navshow');
			$isshow = $_POST['publish'];
			$pid = $_POST['pid'];
			$name = $_POST['name'];
			$path = $pid=="0"?"0":$db->getIpath($pid);
			$data = array(
				'name'=>$name,
				'pid'=>$pid,
				'path'=>$path,
				'isshow'=>$isshow,
				'navshow'=>$navshow,
				'orders'=>(int)$this->_post('orders'),
			);

		
			
			//操作日志内容
			$show = $isshow?"允许发布":"禁止发布";
			$title="添加分类 ".$_POST['name'].' '.$show;
			$content = $title. " 上级栏目id:".$pid;


			
			$result = $db->insert($data);
			if($result){
				//添加分类成功
				actLog($title,$content);//添加操作日志
				$this->success('添加分类成功',__CONTROL__.'/infoList');
				return;
			}else{
				//添加分类失败
				actLog($title,$content,false);//添加操作日志
				$this->error('添加分类失败',__CONTROL__.'/addList');
				return;
			}
		
			
		}else{
			//没有发送数据，显示表单
			$db = K('infoList');
			//$result = $db->where('isshow=1')->all();
			$sql = "select `id`,`name`,`path`,`navshow`,concat(`path`,'-',`id`) as ipath from ica_infoList where 1 order by ipath";
			$r = $db->query($sql);
			if($r){
				$list = $db->getList($r); //获得分类列表项
			}else{
				$list='';
			}
			
			$this->assign('list',$list);
			$this->display();
		}

		
	}

	/**
	 * 编辑分类栏目
	 * @return [type] [description]
	 */
	function editList(){
		if(IS_POST){
			$id = $this->_post('id');//当前栏目id
			if(!$id){
				$this->error('违规操作');
				exit;
			}
			$db = K('infoList');
			$result = $db->field('pid,path')->where("id=$id")->one();
			$opid = $result['pid']; //原pid
			$opath = $result['path']; //原path

			// echo 'opid:'.$opid;
			// echo '<br/>';
			// echo 'opath:'.$opath;
			// echo '<br/>';

			// 新分类栏目
			$pid = $this->_post('pid');//更新至这个分类栏目
			if($pid){
				$path = $db->field('path')->where("id=$pid")->one();
				$path = $path['path'].'-'.$pid;//更新至这个分类栏目的path
			}else{
				$path = '0';
			}


			// echo 'pid:'.$pid;
			// echo '<br/>';

			// echo 'path:'.$path;
			// echo '<br/>';



			// $sql = "update ica_infoList set pid=$pid where id=$id";//更新当前栏目pid
			$sql2 = "update ica_infoList set path=replace(path,'$opath','$path') where id=$id or (path like '".$opath."-$id%')";//更新当前栏目及子栏目的path
			// echo $sql2;
			// p($_POST);
			// exit;
			// 
			// 
			$r1 = $db->save();
			$r2 = $db->runSql($sql2);


			if($r1 && $r2){
				$this->success('更新分类栏目成功',__CONTROL__.'/infoList');
				exit;
			}else{
				$this->error('更新分类栏目失败');
				exit;
			}
			

		}elseif(IS_GET){
			$id = $this->_get('id');
			if(!$id){
				$this->error('违规操作');
				exit;
			}
			$db = K('infoList');

			
			$result = $db->field('pid,path')->where("id=$id")->one();//获得上级分类栏目id（pid）
			$path = $result['path'];
			$sql = "select `id`,`name`,`path`,concat(`path`,'-',`id`) as ipath from ica_infoList where id!=$id and !(path like '$path-$id%') order by ipath";
			// echo $sql;
			
			$arr = $db->query($sql);//查询非本栏目及子栏目的分类

			// p($arr);
			// exit;

			$options = $db->getList($arr,$result['pid']);
			$result = $db->where("id=$id")->one();



			$this->assign('options',$options);//下拉选项
			$this->assign('data',$result);
			$this->display();	
		}
	}
	//删除内容分类
	function delList(){
		$id = @$_GET['id'];
		$url = __CONTROL__.'/infoList';
		if(!$id){//没有传送id，返回
			go($url);
			exit;
		}
		$db = K('infoList');
		$result = $db->where('id='.$id)->one();
		if(!$result){//没有此id数据，返回
			go($url);
			exit;
		}
		$title = "删除内容分类";
		if($db->delList($id)){
			$content=$title.":成功，删除分类id：".$id;
			actLog($title,$content);
			//删除成功
			$this->success("删除成功",$url);
			exit;
		}else{
			$content=$title.":失败";
			actLog($title,$content);
			//删除失败
			$this->error('删除失败',$url);
			exit;
		}
	}
	
	


}
?>